package com.faxsun.core.pricing.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.vendor.service.exception.FulfillmentPriceException;
import org.broadleafcommerce.core.order.domain.FulfillmentGroup;
import org.broadleafcommerce.core.pricing.service.FulfillmentPricingServiceImpl;
import org.broadleafcommerce.core.pricing.service.fulfillment.provider.FulfillmentPricingProvider;

public class FSFulfillmentPricingServiceImpl extends
		FulfillmentPricingServiceImpl {

	protected static final Log LOG = LogFactory
			.getLog(FSFulfillmentPricingServiceImpl.class);

	@Override
	public FulfillmentGroup calculateCostForFulfillmentGroup(
			FulfillmentGroup fulfillmentGroup) throws FulfillmentPriceException {

		for (FulfillmentPricingProvider provider : providers) {
			try {
				if (provider.canCalculateCostForFulfillmentGroup(
						fulfillmentGroup,
						fulfillmentGroup.getFulfillmentOption())) {
					return provider
							.calculateCostForFulfillmentGroup(fulfillmentGroup);
				}
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error(e.getLocalizedMessage());
				continue;
			}
		}

		LOG.error("The FSFulfillmentProvider is not existing");
		LOG.error("There are "+providers.size()+" providers");
		throw new FulfillmentPriceException(
				"No valid processor was found to calculate the FulfillmentGroup cost with "
						+ "FulfillmentOption id: "
						+ fulfillmentGroup.getFulfillmentOption().getId()
						+ " and name: "
						+ fulfillmentGroup.getFulfillmentOption().getName());
	}
}
